// pages/form/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formItem: [],
    idx: [],
    qrcodeList: [],
    logoList: [],
    avatarList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.idx = JSON.parse(options.idx);
    let form = []
    for(var i = 0; i < this.data.idx.length; i++){
      form[i] = app.globalData.form[this.data.idx[i]];
    }
    this.setData({
      formItem: form
    })
  },

  onChange: function(event){
    let id = event.target.id;
    let value = event.detail;
    let form = this.data.formItem;
    form.forEach(i => {
      if(i.id === id){
        i.value = value;
      }
    })
    this.setData({
      formItem: form
    })
  },
  afterRead: function(event){
    const {file, name} = event.detail;
    const id = event.target.id;
    let fileList = [file];
    this.uploadToCloud(fileList, id);
  },
  // 上传图片
  uploadToCloud(fileList, name) {
    wx.cloud.init();
    if (!fileList.length) {
      wx.showToast({ title: '请选择图片', icon: 'none' });
    } else {
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`${name}-${index}.png`, file));
      Promise.all(uploadTasks)
        .then(data => {
          console.log(data)
          wx.showToast({ title: '上传成功', icon: 'none' });
          const url = data[0].fileID;
          const newFileList = [{url: url}];
          if(name == 'qrcode'){
            this.setData({ qrcodeList: newFileList });
          }else if(name == 'logo'){
            this.setData({ logoList: newFileList });
          }else if(name == 'avatar'){
            this.setData({ avatarList: newFileList });
          }     
          this.data.formItem.forEach(i => {
            if (i.id == name) {
              i.value = url;
            }
          });
        })
        .catch(e => {
          wx.showToast({ title: '上传失败', icon: 'none' });
          console.log(e);
        });
    }

  },
  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.path
    });
  },
  next: function(){
    const data = this.data.formItem;
    data.forEach(d => {
      if (d.value == ''){
        Toast(d.name + "还未输入，请输入后再提交");
        return;
      }
    })
    wx.navigateTo({
      url: '../poster/poster?data=' + JSON.stringify(data),
    })

  }
})